Async in Rust
Rust: Future, Async, Await (A Summary)
Stream
futureのiterator。
code: stream.rs
trait Stream {
/// The type of the value yielded by the stream.
type Item;
/// The type representing errors that occurred while processing the computation.
type Error;
/// The function that will be repeatedly called to see if the stream has
/// another value it can yield
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error>;
}
Tokio runtime
futureのpollをコールする。
Creating Runtime does the following:
Spawn a background thread running a Reactor instance.
Start a ThreadPool for executing futures.
Run an instance of Timer per thread pool worker thread.
run functionはruntimeがidleになるまでブロックする。
spawnされた全てのタスクが完了(thread poolが実行するタスクを持たない)
reactorの扱うI/O resourceがなくなるまで。
code:runtime.rs
use tokio::net::TcpListener;
let listener = TcpListener::bind(&addr).unwrap();
let server = listener.incoming()
.map_err(|e| println!("error = {:?}", e))
.for_each(|socket| {
tokio::spawn(process(socket))
});
tokio::run(server);
Hyper
hyper::rt::lazy:遅延処理用の関数をFutureとしてwrap。
hyper::rt::run:tokio runtimeを実行